package com.eliota.utils;

/*import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.Date;*/

/**
 * @author M.G
 * @create 2023-03-27 22:55
 * @date 2023/3/27 22:55
 */
public class JJWTDemo {

   /* //有效时间，单位毫秒
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //签名密码
    private static String tokenSignKey = "123456";

    //根据用户id和密码生成用户的token字符串
    public static String createToken(Integer userId, String username) {
        String token = Jwts.builder()
                //分类
                .setSubject("AUTH-USER")
                //设置token的有效时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //设置主体部分
                .claim("userId", userId)
                .claim("username", username)
                //签名部分
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //从生成的token字符串中获取用户Id
    public static Integer getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws IOException {
        String token = JJWTDemo.createToken(1, "admin");

        // 创建Base64解码器
        BASE64Decoder base64Decoder = new BASE64Decoder();
        // 执行Base64解码操作，因为编码的时候操作对象就是字节数组，所以解码的返回值也是一个字节数组
        String s = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ==";
        byte[] bytes = base64Decoder.decodeBuffer(s);
        // 使用指定的字符集解码指定的字节数组，构造一个新的String
        String string = new String(bytes, "UTF-8");
        System.err.println(string);

        System.out.println(token);
        System.out.println(JJWTDemo.getUserId(token));
        System.out.println(JJWTDemo.getUsername(token));
    }
*/
}
